Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes' values.
(ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[[3], [9,20], [15,7]]

题目大意:层次遍历给定二叉树

题目难度:Easy

import java.util.*;
/**
 * Created by gzdaijie on 16/6/7
 */
public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;

        queue.offer(root);
        while (true) {
            List<Integer> item = new ArrayList<>();
            int size = queue.size();
            if (size == 0) return result;
            while (size-- > 0) {
                TreeNode tmp = queue.poll();
                item.add(tmp.val);
                if (tmp.left != null) queue.offer(tmp.left);
                if (tmp.right != null) queue.offer(tmp.right);
            }
            result.add(item);
        }
    }
}
gzdaijie            updated 2016-06-07 13:40:56

results matching ""

    No results matching ""